import { useStore } from '@/hooks';
import { Button, Dialog, Icon, Form, ResponsiveGrid, Drawer, Message } from '@alifd/next';
import TauTable from '@/components/TauTable';
import UploadPanel from '@/components/UploadPanel';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, column, vehicleModel } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable, toJS } from 'mobx';
import AttachmentForm from './AttachmentForm';
import Driver from '../../Driver/components/DataForm';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

const CrossForm = ({ modal, vehicleInfo, onCancel, onSubmit }) => {
  const { vehicleStore: store, driverStore } = useStore();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal[0] === 'viewCross');
  const formProps = isViewMode ? { field: false } : {};
  const [vehicle] = useState(() => observable({}));
  const driverRef = useRef();
  const pageRef = useRef(0);
  const [driver, setDriver] = useState([]);

  useEffect(() => {
    if (modal[1]?.startsWith?.('toClose')) handleCancel();
  }, [modal]);

  useEffect(() => {
    (async () => {
      if (JSON.stringify(vehicleInfo) !== '{}') {
        const data = vehicleInfo;
        editCtx.origin = _.cloneDeep(data);
        _.assign(vehicle, data);
        await store.getDriver({ companyId: data.companyId, type: '1', size: 10 });
        await store.getCompany({ search: { status: 1 }, pg: { size: 999 } });
      } else {
        _.set(vehicle, 'status', 1);
        _.set(vehicle, 'type', 1);
      }
    })();
    return () => {
      pageRef.current = 0;
    };
  }, []);

  const onScroll = async (e) => {
    const target = e.target;
    const scrollHeight = target.scrollHeight;
    const clientHeight = target.clientHeight;
    const scrollTop = target.scrollTop;

    if (scrollTop + clientHeight === scrollHeight) {
      pageRef.current += 1;
      await store.getDriver({ companyId: vehicle.companyId, type: '1', page: pageRef.current });
    }
  };

  /**
   * 页面重载
   */
  const overrideModel = {
    coDrivers: {
      label: t`副司机`,
      ui: {
        renderer: (v) => (
          <TauSimpleSelect
            showSearch
            value={v}
            data={store.drivers}
            mode="multiple"
            menuProps={{ onScroll }}
            autoHighlightFirstItem={false}
          />
        ),
        itemProps: { required: true },
      },
    },
  };

  /**
   * 添加司机
   */
  const handleAddDriver = () => {
    if (vehicle?.companyId === undefined) {
      return Message.error({ content: t`请先选择公司` });
    }
    driverRef.current = vehicle;
    setDriver(['add']);
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = async (values, item) => {
    const { name, value } = item;
    // eslint-disable-next-line eqeqeq
    if (name === 'companyId') {
      await store.getDriver({ companyId: value, type: '1', page: 0 });
    }
    _.set(vehicle, name, value);
    editCtx.changed[name] = value === _.get(editCtx.origin, name) ? undefined : value;
  };

  /**
   * @description 提交表单实现修改车辆
   * @param {*} r formData
   */
  const handleSubmit = async (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    onSubmit?.(vehicle);
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  /**
   * 关闭添加司机
   * @returns
   */
  const handleCancelDriver = () => {
    setDriver([]);
  };

  /**
   * 添加司机
   * @param {*} result
   */
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        result.accountId = result.mobile;
        await driverStore.create(toJS(result));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      } finally {
        store.getDriver({ companyId: vehicle.companyId, type: '1', page: 0 });
      }
    }
    setDriver([]);
  };

  return (
    <>
      <Form
        inline
        {...formProps}
        value={vehicle}
        isPreview={isViewMode}
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <TitleGrid title={t`基础信息`} />
        <FieldsGrid
          formData={vehicle}
          mode={isViewMode ? 'view' : modal[0]}
          fields={[
            'companyId',
            'licenseNo.mainland',
            'licenseNo.hk',
            'landCompany',
            'hkCompany',
            'vin',
            'engine',
            'carType',
            'vehicle',
            'validityDateOfAnnualReview',
            'validityDateOfEntryExit',
            'vehicleType',
            'vehicleColor',
            'numberOfSeats',
            'dateOfDelivery',
            'manufacturer',
            'firstTime',
            'tude',
            'status',
          ]}
        />
        <TitleGrid
          title={
            <>
              <span>{t`业务信息`}</span>
              <Button
                type="primary"
                style={{ marginLeft: 10 }}
                onClick={() => handleAddDriver()}
              >{t`添加副司机`}</Button>
            </>
          }
        />
        <FieldsGrid
          formData={vehicle}
          mode={isViewMode ? 'view' : modal[0]}
          overrideModel={!isViewMode && overrideModel}
          fields={['mainDriver', 'coDrivers', 'permanentLand', 'ports']}
        />
        <TitleGrid title={t`附件及备注`} />
        <FieldsGrid formData={vehicle} mode={isViewMode ? 'view' : modal[0]} fields={['remark']} />
        <AttachmentPanel vehicle={vehicle} mode={modal[0]} />
        <DrawerFooter>
          <FromItem>
            {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>
      </Form>
      <Drawer
        visible={!!driver[0]}
        title={t`添加司机`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setDriver([...driver, `toClose$${Date.now()}`])}
        width="85%"
      >
        <Driver
          addDriver={driverRef.current}
          modal={driver}
          driverInfo={{}}
          onCancel={() => handleCancelDriver()}
          onSubmit={handleCreate}
        />
      </Drawer>
    </>
  );
};

/**
 * @description 附件组件
 */
const AttachmentPanel = observer(({ vehicle, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'viewCross';

  useEffect(() => {
    if (vehicle?.attachments?.length) setIdx(0);
  }, [vehicle?.attachments]);

  const handleAddAttachment = () => {
    if (!vehicle?.attachments) vehicle.attachments = [];
    vehicle.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(vehicle.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    vehicle.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid
        title={
          <span>
            {t`附件`}
            {mode !== 'view' && (
              <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment}>{t`添加附件`}</Button>
            )}
          </span>
        }
      />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={7}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(vehicle?.attachments)}
            cellProps={(r) => ({
              style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' },
            })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, vehicleModel.driverInfo.attachments[0]),
              column('description', {}, vehicleModel.driverInfo.attachments[0]),
              {
                title: t`附件个数`,
                dataIndex: 'cnt',
                width: 84,
                cell: (_, i, row) => (
                  <Button type="primary" text>
                    {row.binaryId?.length}
                  </Button>
                ),
              },
            ].concat(
              isViewMode
                ? [
                    {
                      align: 'left',
                      width: 30,
                      cell: (_, i) =>
                        i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />,
                    },
                  ]
                : [
                    {
                      title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                      dataIndex: 'title',
                      align: 'left',
                      width: 110,
                      cell: (_, i, row) => (
                        <span>
                          <Button type="primary" text onClick={() => setCurAttachment(row)}>{t`编辑`}</Button>
                          <span> </span>
                          <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)}>{t`删除`}</Button>
                          {i === idx && (
                            <Icon
                              type="arrow-right"
                              size="xs"
                              style={{ marginLeft: 16, color: 'var(--color-line1-4)' }}
                            />
                          )}
                        </span>
                      ),
                    },
                  ],
            )}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && (
            <UploadPanel
              isPreview={isViewMode}
              prefix={`chanel:${vehicle.id}:attachment`}
              binaryIds={idx === -1 ? [] : toJS(vehicle.attachments[idx]?.binaryId)}
              onUploaded={(meta) => {
                vehicle.attachments[idx]?.binaryId.push(meta.binaryId);
              }}
              onRemove={(info) => {
                vehicle.attachments[idx]?.binaryId.splice(
                  vehicle.attachments[idx]?.binaryId.findIndex((r) => r == info.uid),
                  1,
                );
              }}
            />
          )}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(vehicle.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});

export default observer(CrossForm);
